/**
 * *************************************
 * Copyright(c)2016 Dingdang Yixia 
 * All Rights Reserved.
 *
 * @File: WdgjCouldClient.java
 * @Package: com.wdgj.sdk.util
 * @Description:
 * 
 * @Version: V1.0
 * @Author: Yidong.Xiang
 * @Date: 2018年9月6日 下午3:31:32
 * 
 * *************************************
 */
package com.wdgj.sdk.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;

import com.wdgj.sdk.config.WdgjCouldServer;
import com.wdgj.sdk.model.base.WdgjSignRequest;


/**
 * @ClassName: WdgjCouldClient.java
 * @Module: 	网店管家开发接口访问工具类
 * @Description: 	接口传到参数的数据签名
 * 
 * @author: Yidong.Xiang
 * @date: 2018年9月6日 下午3:31:32
 * 
 */
public class WdgjCloudClient {
	private static Logger log = Logger.getLogger(WdgjCloudClient.class);
	 
	/**
	 *  生成签名
	 * @param paraMap
	 * @return
	 */
    private static String getSign(Map<String, String> paraMap) {
        Iterator<Entry<String,String>> iter = paraMap.entrySet().iterator();
        List<String> list = new ArrayList<String>();
        while (iter.hasNext()) {
            Map.Entry<String,String> entry = (Map.Entry<String,String>) iter.next();
            String val = entry.getValue().toString();
            list.add(val);
        }
        //ASCII码排序
        Collections.sort(list, new Comparator<String>() {
            public int compare(String o1, String o2) {
                return o1.compareTo(o2);
            }
        });
        StringBuilder builder = new StringBuilder();
        //参数拼接
        builder.append(WdgjCouldServer.getInstance().getValue("wdgj.appsecret"));
        for (String value : list) {
            builder.append(value);
        }
        builder.append(WdgjCouldServer.getInstance().getValue("wdgj.appsecret"));
        //md5加密后得到最终的签名
        return getMd5Value(builder.toString());
    }
   
    /**
     *  自己处理一下md5加密，原生的md5加密方法有问题
     * @param sSecret
     * @return
     */
    private static String getMd5Value(String sSecret) {
        StringBuffer buf = new StringBuffer();
    	try {
            MessageDigest bmd5 = MessageDigest.getInstance("MD5");
            bmd5.update(sSecret.getBytes("UTF-8"));
            int i;
            byte[] b = bmd5.digest();
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
        return buf.toString();
    }
//    /**
//     *   收集签名需要的参数
//     * @param requestParam
//     * @return
//     */
//    public static String getSign(WdgjSignRequest requestParam) {
//        HashMap<String, String> map = new HashMap<String,String>();
//        map.put("Appkey", WdgjApiConfig.appkey);
//        map.put("Accesstoken", WdgjApiConfig.accesstoken);
//        map.put("Format",requestParam.getFormat());
//        map.put("Timestamp", requestParam.getTimestamp());
//        map.put("Versions", requestParam.getVersions());
//        map.put("Method",requestParam.getMethod());
//        map.put("Content",requestParam.getContent());
//        //map.put（除appsecret参数外的所有系统级参数和应用级级参数值，根据每个方法需要传的参数）
//        return getSign(map);
//    }
    /**
	 *   向指定 URL 发送POST方法的请求
	 * 
	 * @param url 发送请求的 URL
	 * @param param 请求参数
	 * @return 所代表远程资源的响应结果
	 */
	public static String sendPost(WdgjSignRequest requestParam) {
	    PrintWriter out = null;
	    BufferedReader in = null;
	    String result = "";
	    StringBuffer param = new StringBuffer("");
	    String connect = WdgjCouldServer.getInstance().getValue("wdgj.connect");
	    String debug = WdgjCouldServer.getInstance().getValue("wdgj.debug");
	    if(!"true".equalsIgnoreCase(connect))
	    	return "{  \"error_code\": \"-1\",  \"error_info\": \"connect is false at wdgj open api properties setting \"}";
	    try {
//	    	param.append("Appkey=").append(URLEncoder.encode(WdgjApiConfig.appkey,"utf-8"));
//			param.append("&Accesstoken=").append(URLEncoder.encode(WdgjApiConfig.accesstoken,"utf-8"));
//			param.append("&Method=").append(URLEncoder.encode(requestParam.getMethod(),"utf-8"));
//			param.append("&Sign=").append(URLEncoder.encode(getSign(requestParam),"utf-8"));
//			param.append("&Timestamp=").append(URLEncoder.encode(requestParam.getTimestamp(),"utf-8"));
//			param.append("&Format=").append(URLEncoder.encode(requestParam.getFormat(),"utf-8"));
//			param.append("&Versions=").append(URLEncoder.encode(requestParam.getVersions(),"utf-8"));
//			param.append("&content=").append(URLEncoder.encode(requestParam.getContent(),"utf-8"));
//			//收集签名需要的参数
			HashMap<String, String> paramMap = new HashMap<String,String>();
			paramMap.put("Appkey", WdgjCouldServer.getInstance().getValue("wdgj.appkey"));
			paramMap.put("Accesstoken", WdgjCouldServer.getInstance().getValue("wdgj.accesstoken"));
			paramMap.put("Format",requestParam.getFormat());
			paramMap.put("Timestamp", requestParam.getTimestamp());
			paramMap.put("Versions", requestParam.getVersions());
			paramMap.put("Method",requestParam.getMethod());
			paramMap.put("Content",requestParam.getContent());
			paramMap.put("Sign", getSign(paramMap));
			Iterator<String> it = paramMap.keySet().iterator();
			while(it.hasNext()) {
				String key = it.next();
				String value = URLEncoder.encode(paramMap.get(key).toString(),"utf-8");
				param.append(key).append("=").append(value).append("&");
			}
		
	        URL realUrl = new URL(WdgjCouldServer.getInstance().getValue("wdgj.url"));
	        // 打开和URL之间的连接
	        URLConnection conn = realUrl.openConnection();
	        // 设置通用的请求属性
	        conn.setRequestProperty("accept", "*/*");
	        conn.setRequestProperty("connection", "Keep-Alive");
	        conn.setRequestProperty("Accept-Charset", "utf-8");
	        conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
	        // 发送POST请求必须设置如下两行
	        conn.setDoOutput(true);
	        conn.setDoInput(true);
	        // 获取URLConnection对象对应的输出流
	        out = new PrintWriter(conn.getOutputStream());
	        // 发送请求参数
	        out.print(param.toString());
	        // flush输出流的缓冲
	        out.flush();
	        // 定义BufferedReader输入流来读取URL的响应
	        in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
	        String line;
	        while ((line = in.readLine()) != null) {
	            result += line;
	        }
	        if("true".equalsIgnoreCase(debug))
	        	System.out.println(result);
	    } catch (Exception e) {
	    	log.error(e.getMessage(), e);
	    }
	    //使用finally块来关闭输出流、输入流
	    finally{
	        try{
	            if(out!=null){
	                out.close();
	            }
	            if(in!=null){
	                in.close();
	            }
	        }
	        catch(IOException ex){
	            ex.printStackTrace();
	        }
	    }
	    return result;
	}	
}
